/**
 * 固定资产管理系统 5.0 - 高级功能模块
 * 包含性能监控、数据可视化、实时更新等高级功能
 * 版本: v5.0.0 Ultimate Edition
 */

class AdvancedFeatures {
    constructor() {
        this.charts = new Map();
        this.realTimeData = new Map();
        this.intervals = new Map();
        this.init();
    }

    // 在资产日志/模态上下文中抑制交互与动画，避免闪烁
    isSuppressedContext() {
        try {
            return (
                document.body.classList.contains('modal-open') ||
                !!document.querySelector('.modal.show') ||
                !!document.querySelector('#assetLogsContainer') ||
                !!document.querySelector('.asset-logs') ||
                !!document.querySelector('.related-logs')
            );
        } catch (e) { return false; }
    }

    init() {
        console.log('🚀 初始化高级功能模块...');
        
        this.initializeCharts();
        this.initializeRealTimeUpdates();
        this.initializeKeyboardShortcuts();
        this.initializeContextMenu();
        this.initializeDataExport();
        this.initializeAdvancedSearch();
        
        console.log('✅ 高级功能模块加载完成');
    }

    // 初始化图表组件
    initializeCharts() {
        console.log('📊 初始化图表组件...');
        
        // 创建环形图
        this.createDonutChart('asset-usage-chart', {
            data: [
                { label: '使用中', value: 75, color: '#059669' },
                { label: '空闲', value: 20, color: '#d97706' },
                { label: '维修', value: 5, color: '#dc2626' }
            ],
            total: 100
        });

        // 创建趋势图
        this.createTrendChart('performance-trend', {
            data: this.generateTrendData(),
            labels: ['响应时间', 'CPU使用', '内存使用', '并发用户']
        });
    }

    // 创建环形图
    createDonutChart(containerId, config) {
        const container = document.getElementById(containerId);
        if (!container) return;

        const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('width', '120');
        svg.setAttribute('height', '120');
        svg.style.transform = 'rotate(-90deg)';

        const radius = 50;
        const centerX = 60;
        const centerY = 60;
        const circumference = 2 * Math.PI * radius;

        let currentAngle = 0;

        config.data.forEach((segment, index) => {
            const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
            circle.setAttribute('cx', centerX);
            circle.setAttribute('cy', centerY);
            circle.setAttribute('r', radius);
            circle.setAttribute('fill', 'none');
            circle.setAttribute('stroke', segment.color);
            circle.setAttribute('stroke-width', '8');
            circle.setAttribute('stroke-linecap', 'round');

            const percentage = segment.value / config.total;
            const strokeLength = circumference * percentage;
            const strokeOffset = circumference - strokeLength;

            circle.style.strokeDasharray = `${strokeLength} ${circumference}`;
            circle.style.strokeDashoffset = circumference - currentAngle * circumference;
            // 在抑制上下文中禁用过渡动画
            if (this.isSuppressedContext()) {
                circle.style.transition = 'none';
            } else {
                circle.style.transition = 'stroke-dasharray 2s ease, stroke-dashoffset 2s ease';
            }

            currentAngle += percentage;
            svg.appendChild(circle);
        });

        container.appendChild(svg);
        this.charts.set(containerId, { svg, config });
    }

    // 创建趋势图
    createTrendChart(containerId, config) {
        const container = document.getElementById(containerId);
        if (!container) return;

        const canvas = document.createElement('canvas');
        canvas.width = container.offsetWidth || 300;
        canvas.height = 150;
        canvas.style.width = '100%';
        canvas.style.height = '150px';

        const ctx = canvas.getContext('2d');
        this.drawTrendLines(ctx, config.data, canvas.width, canvas.height);

        container.appendChild(canvas);
        this.charts.set(containerId, { canvas, ctx, config });
    }

    // 绘制趋势线
    drawTrendLines(ctx, data, width, height) {
        ctx.clearRect(0, 0, width, height);
        
        const padding = 20;
        const chartWidth = width - padding * 2;
        const chartHeight = height - padding * 2;

        // 绘制网格
        ctx.strokeStyle = '#e5e7eb';
        ctx.lineWidth = 1;
        
        for (let i = 0; i <= 5; i++) {
            const y = padding + (chartHeight / 5) * i;
            ctx.beginPath();
            ctx.moveTo(padding, y);
            ctx.lineTo(width - padding, y);
            ctx.stroke();
        }

        // 绘制数据线
        const colors = ['#3b82f6', '#059669', '#d97706', '#dc2626'];
        
        data.forEach((series, seriesIndex) => {
            ctx.strokeStyle = colors[seriesIndex % colors.length];
            ctx.lineWidth = 2;
            ctx.beginPath();

            series.forEach((value, index) => {
                const x = padding + (chartWidth / (series.length - 1)) * index;
                const y = height - padding - (value / 100) * chartHeight;

                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });

            ctx.stroke();
        });
    }

    // 生成趋势数据
    generateTrendData() {
        const data = [];
        for (let i = 0; i < 4; i++) {
            const series = [];
            for (let j = 0; j < 12; j++) {
                series.push(Math.random() * 100);
            }
            data.push(series);
        }
        return data;
    }

    // 初始化实时更新
    initializeRealTimeUpdates() {
        console.log('🔄 启动实时数据更新...');

        // 性能指标更新
        this.intervals.set('performance', setInterval(() => {
            this.updatePerformanceMetrics();
        }, 5000));

        // 活动时间轴更新
        this.intervals.set('timeline', setInterval(() => {
            this.updateTimeline();
        }, 15000));

        // 实时统计更新
        this.intervals.set('stats', setInterval(() => {
            this.updateRealTimeStats();
        }, 10000));
    }

    // 更新性能指标
    updatePerformanceMetrics() {
        const metrics = [
            { selector: '.metric-item:nth-child(1) .metric-value', range: [35, 65], unit: 'ms' },
            { selector: '.metric-item:nth-child(2) .metric-value', range: [60, 85], unit: '%' },
            { selector: '.metric-item:nth-child(3) .metric-value', range: [15, 40], unit: '%' },
            { selector: '.metric-item:nth-child(4) .metric-value', range: [8, 20], unit: '人' }
        ];

        metrics.forEach(metric => {
            const element = document.querySelector(metric.selector);
            if (element) {
                const [min, max] = metric.range;
                const newValue = Math.floor(Math.random() * (max - min + 1)) + min;
                
                const suppressed = this.isSuppressedContext();
                if (suppressed) {
                    // 直接更新数值，禁用缩放动画
                    element.style.transition = 'none';
                    const unitSpan = element.querySelector('.metric-unit');
                    element.innerHTML = `${newValue}<span class="metric-unit">${metric.unit}</span>`;
                    element.style.transform = 'none';
                } else {
                    // 动画效果
                    element.style.transition = 'transform 0.3s ease';
                    element.style.transform = 'scale(1.1)';
                    
                    setTimeout(() => {
                        const unitSpan = element.querySelector('.metric-unit');
                        element.innerHTML = `${newValue}<span class="metric-unit">${metric.unit}</span>`;
                        element.style.transform = 'scale(1)';
                    }, 150);
                }
            }
        });
    }

    // 更新时间轴
    updateTimeline() {
        const activities = [
            { title: '新设备入库', desc: 'MacBook Pro M2 已成功入库，资产编号：AS001456', type: 'success' },
            { title: '用户权限变更', desc: '用户 王五 权限已提升为管理员', type: '' },
            { title: '系统维护', desc: '系统性能优化完成，响应速度提升 20%', type: 'success' },
            { title: '资产调拨', desc: '10台显示器从IT部门调拨至财务部', type: 'warning' },
            { title: '安全扫描', desc: '系统安全扫描完成，未发现安全漏洞', type: 'success' }
        ];

        const randomActivity = activities[Math.floor(Math.random() * activities.length)];
        this.addTimelineItem(randomActivity.title, randomActivity.desc, randomActivity.type);
    }

    // 添加时间轴项目
    addTimelineItem(title, description, type = '') {
        const timelineList = document.querySelector('.timeline-list');
        if (!timelineList) return;

        const newItem = document.createElement('div');
        newItem.className = `timeline-item ${type}`;
        newItem.innerHTML = `
            <div class="timeline-content">
                <div class="timeline-title">${title}</div>
                <div class="timeline-desc">${description}</div>
                <div class="timeline-time">刚刚</div>
            </div>
        `;

        // 添加到顶部
        timelineList.insertBefore(newItem, timelineList.firstChild);

        const suppressed = this.isSuppressedContext();
        if (suppressed) {
            // 直接呈现最终状态，禁用过渡动画
            newItem.style.transition = 'none';
            newItem.style.opacity = '1';
            newItem.style.transform = 'none';
        } else {
            // 动画效果
            newItem.style.opacity = '0';
            newItem.style.transform = 'translateX(-20px)';
            setTimeout(() => {
                newItem.style.transition = 'all 0.5s ease';
                newItem.style.opacity = '1';
                newItem.style.transform = 'translateX(0)';
            }, 100);
        }

        // 限制时间轴项目数量
        const items = timelineList.querySelectorAll('.timeline-item');
        if (items.length > 8) {
            items[items.length - 1].remove();
        }

        // 显示通知
        this.showNotification('实时更新', title, 'info');
    }

    // 更新实时统计
    updateRealTimeStats() {
        const stats = document.querySelectorAll('.counter');
        stats.forEach(counter => {
            const currentValue = parseInt(counter.textContent.replace(/,/g, ''));
            const variation = Math.floor(Math.random() * 10) - 5; // -5 到 +5 的变化
            const newValue = Math.max(0, currentValue + variation);
            
            this.animateCounter(counter, newValue);
        });
    }

    // 动画计数器
    animateCounter(element, targetValue) {
        const currentValue = parseInt(element.textContent.replace(/,/g, ''));
        const difference = targetValue - currentValue;
        const steps = 20;
        const stepValue = difference / steps;
        let currentStep = 0;

        const timer = setInterval(() => {
            currentStep++;
            const newValue = Math.floor(currentValue + stepValue * currentStep);
            element.textContent = newValue.toLocaleString();

            if (currentStep >= steps) {
                clearInterval(timer);
                element.textContent = targetValue.toLocaleString();
            }
        }, 50);
    }

    // 初始化键盘快捷键
    initializeKeyboardShortcuts() {
        const shortcuts = {
            'KeyE': () => this.exportCurrentView(),
            'KeyR': () => this.refreshAllData(),
            'KeyF': () => this.toggleFullscreen(),
            'KeyH': () => this.showHelpDialog()
        };

        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                const action = shortcuts[e.code];
                if (action) {
                    e.preventDefault();
                    action();
                }
            }
        });

        console.log('⌨️ 键盘快捷键已启用: Ctrl+E(导出), Ctrl+R(刷新), Ctrl+F(全屏), Ctrl+H(帮助)');
    }

    // 初始化右键菜单
    initializeContextMenu() {
        document.addEventListener('contextmenu', (e) => {
            if (e.target.closest('.stats-card, .management-module')) {
                e.preventDefault();
                this.showContextMenu(e.pageX, e.pageY, e.target);
            }
        });

        document.addEventListener('click', () => {
            this.hideContextMenu();
        });
    }

    // 显示右键菜单
    showContextMenu(x, y, target) {
        this.hideContextMenu(); // 先隐藏已有菜单

        const menu = document.createElement('div');
        menu.className = 'context-menu show';
        menu.style.left = x + 'px';
        menu.style.top = y + 'px';

        const menuItems = [
            { icon: 'fas fa-eye', text: '查看详情', action: () => this.viewDetails(target) },
            { icon: 'fas fa-edit', text: '编辑', action: () => this.editItem(target) },
            { icon: 'fas fa-copy', text: '复制信息', action: () => this.copyInfo(target) },
            { divider: true },
            { icon: 'fas fa-download', text: '导出数据', action: () => this.exportData() },
            { icon: 'fas fa-sync-alt', text: '刷新', action: () => this.refreshData() }
        ];

        menuItems.forEach(item => {
            if (item.divider) {
                const divider = document.createElement('div');
                divider.className = 'context-menu-divider';
                menu.appendChild(divider);
            } else {
                const menuItem = document.createElement('div');
                menuItem.className = 'context-menu-item';
                menuItem.innerHTML = `<i class="${item.icon}"></i> ${item.text}`;
                menuItem.addEventListener('click', (e) => {
                    e.stopPropagation();
                    item.action();
                    this.hideContextMenu();
                });
                menu.appendChild(menuItem);
            }
        });

        document.body.appendChild(menu);
        this.contextMenu = menu;
    }

    // 隐藏右键菜单
    hideContextMenu() {
        if (this.contextMenu) {
            this.contextMenu.remove();
            this.contextMenu = null;
        }
    }

    // 初始化数据导出
    initializeDataExport() {
        this.exportFormats = ['Excel', 'CSV', 'PDF', 'JSON'];
        console.log('💾 数据导出功能已初始化');
    }

    // 初始化高级搜索
    initializeAdvancedSearch() {
        const searchInput = document.getElementById('globalSearch');
        if (!searchInput) return;

        // 搜索历史
        this.searchHistory = JSON.parse(localStorage.getItem('searchHistory') || '[]');
        
        // 高级搜索语法
        this.searchOperators = {
            'type:': '按类型搜索 (type:laptop)',
            'status:': '按状态搜索 (status:active)',
            'dept:': '按部门搜索 (dept:IT)',
            'user:': '按用户搜索 (user:张三)',
            'date:': '按日期搜索 (date:2024-01)',
            'value:': '按价值搜索 (value:>1000)'
        };

        console.log('🔍 高级搜索功能已启用');
    }

    // 显示通知
    showNotification(title, message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification-toast ${type}`;
        notification.innerHTML = `
            <div class="notification-header">
                <div class="notification-title">${title}</div>
                <button class="notification-close">&times;</button>
            </div>
            <div class="notification-body">${message}</div>
        `;

        document.body.appendChild(notification);
        const suppressed = this.isSuppressedContext();
        if (suppressed) {
            // 立即显示并禁用过渡
            notification.style.transition = 'none';
            notification.classList.add('show');
        } else {
            setTimeout(() => {
                notification.classList.add('show');
            }, 100);
        }

        notification.querySelector('.notification-close').addEventListener('click', () => {
            this.hideNotification(notification);
        });

        setTimeout(() => {
            this.hideNotification(notification);
        }, 5000);
    }

    // 隐藏通知
    hideNotification(notification) {
        const suppressed = this.isSuppressedContext();
        if (suppressed) {
            // 立即移除
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        } else {
            notification.classList.remove('show');
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }
    }

    // 快捷键功能
    exportCurrentView() {
        this.showNotification('导出数据', '正在导出当前视图数据...', 'info');
        setTimeout(() => {
            this.showNotification('导出完成', '数据已成功导出为Excel文件', 'success');
        }, 2000);
    }

    refreshAllData() {
        this.showNotification('刷新数据', '正在刷新所有数据...', 'info');
        this.updatePerformanceMetrics();
        this.updateRealTimeStats();
        setTimeout(() => {
            this.showNotification('刷新完成', '所有数据已更新到最新状态', 'success');
        }, 1500);
    }

    toggleFullscreen() {
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen().then(() => {
                this.showNotification('全屏模式', '已进入全屏模式，按 ESC 退出', 'info');
            });
        } else {
            document.exitFullscreen();
        }
    }

    showHelpDialog() {
        const helpContent = `
            <div style="text-align: left; line-height: 1.6;">
                <h3 style="color: #1e3a8a; margin-bottom: 15px;">🎯 快捷键说明</h3>
                <ul style="list-style: none; padding: 0;">
                    <li><strong>Ctrl+K</strong> - 激活全局搜索</li>
                    <li><strong>Ctrl+E</strong> - 导出当前数据</li>
                    <li><strong>Ctrl+R</strong> - 刷新所有数据</li>
                    <li><strong>Ctrl+F</strong> - 切换全屏模式</li>
                    <li><strong>ESC</strong> - 关闭对话框/全屏</li>
                </ul>
                
                <h3 style="color: #1e3a8a; margin: 20px 0 15px 0;">🔍 搜索语法</h3>
                <ul style="list-style: none; padding: 0;">
                    <li><code>type:laptop</code> - 搜索笔记本电脑</li>
                    <li><code>status:active</code> - 搜索使用中的资产</li>
                    <li><code>dept:IT</code> - 搜索IT部门的资产</li>
                    <li><code>value:>1000</code> - 搜索价值大于1000的资产</li>
                </ul>
                
                <h3 style="color: #1e3a8a; margin: 20px 0 15px 0;">💡 功能提示</h3>
                <ul style="list-style: none; padding: 0;">
                    <li>• 右键点击卡片可显示更多操作</li>
                    <li>• 点击表格标题可进行排序</li>
                    <li>• 选择多行可进行批量操作</li>
                    <li>• 数据每10秒自动更新一次</li>
                </ul>
            </div>
        `;

        this.showModal('系统帮助', helpContent);
    }

    // 显示模态框
    showModal(title, content) {
        const modal = document.createElement('div');
        modal.className = 'fullscreen-overlay show';
        modal.innerHTML = `
            <div class="fullscreen-content" style="max-width: 600px; max-height: 80vh;">
                <div class="fullscreen-header">
                    <div class="fullscreen-title">
                        <i class="fas fa-question-circle"></i>
                        ${title}
                    </div>
                    <button class="fullscreen-close" onclick="this.closest('.fullscreen-overlay').remove(); document.body.style.overflow = '';">&times;</button>
                </div>
                <div class="fullscreen-body">
                    ${content}
                </div>
            </div>
        `;

        document.body.appendChild(modal);
        document.body.style.overflow = 'hidden';
    }

    // 上下文菜单操作
    viewDetails(target) {
        const title = target.querySelector('h3')?.textContent || '详细信息';
        this.showNotification('查看详情', `正在加载 ${title} 的详细信息...`, 'info');
    }

    editItem(target) {
        const title = target.querySelector('h3')?.textContent || '项目';
        this.showNotification('编辑模式', `进入 ${title} 编辑模式`, 'info');
    }

    copyInfo(target) {
        const title = target.querySelector('h3')?.textContent || '信息';
        navigator.clipboard.writeText(title).then(() => {
            this.showNotification('复制成功', '信息已复制到剪贴板', 'success');
        });
    }

    // 清理函数
    cleanup() {
        // 清理所有定时器
        this.intervals.forEach((interval, key) => {
            clearInterval(interval);
        });
        this.intervals.clear();

        // 清理事件监听器
        this.hideContextMenu();

        console.log('🧹 高级功能模块已清理');
    }
}

// 自动初始化
document.addEventListener('DOMContentLoaded', function() {
    // 延迟初始化，确保其他组件已加载
    setTimeout(() => {
        window.advancedFeatures = new AdvancedFeatures();
        console.log('🎉 固定资产管理系统 5.0 - 高级功能模块已全面启动！');
    }, 1000);
});

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    if (window.advancedFeatures) {
        window.advancedFeatures.cleanup();
    }
});